/**
 * @desc 用户修改组件
 */
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { Form, Space, Button, Input } from "antd";
import { phoneReg, passwordReg } from '@/utils/regexp'
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { apiUserUpdate, apiUserDetails, apiGetUpdateRolesByUserId } from "@/request/system/user";

const Item = Form.Item;

class UserUpdate extends Component {
  state = {
    loading: false,
    dataSource: null
  }

  async componentDidMount() {
    if (this.props.id) {
      const res = await apiUserDetails({ userId: this.props.id })
      if (res.code === 0 && res.data) {
        
        let data = JSON.parse(JSON.stringify(res.data))
        console.log(data);
        data.roleIds = data.roleIds.split(',')
        this.formRef.setFieldsValue(data)
        this.setState({
          dataSource: res.data
        })
      }
    }
  }

  /**
   * @desc 新增提交事件
   * @params object {value} 表单验证对象
   * */
  onFinish = async value => {
    value.userId = this.props.id
    const keys = Object.keys(value)
    console.log(keys);
    console.log(value);
    keys.forEach(v => {
      if(v==="storeId"){
        value[v] =  value[v] ? value[v] :"" 
      }else{
        if (!value[v]) {
          delete value[v]
        }
      }
    })
    // return
    this.setState({ loading: true })
    apiUserUpdate(value).then(async res => {
      if (res.code === 0) {
        const response = await apiGetUpdateRolesByUserId({ userId: value.userId, roleIds: value.roleIds })
        if (response.code === 0) {
          React.$message({
            type: 'success',
            content: '修改成功'
          })
          //关闭弹窗
          this.props.handleCancel()
          //刷新你列表
          this.props.getList();
        }
      }
      this.setState({ loading: false })
    }).catch(e => {
      this.setState({ loading: false })
    })
  };
  /**
   * @desc 确认自定义密码验证
   * @params Reg {rule} 验证规则
   * @params string {value} 需要验证的字符串
   * @params fun {callback} 回调函数
   * */
  validatePassword = (rule, value, callback) => {
    const password = this.formRef.getFieldsValue(['passwdMd']).passwdMd;
    if (value !== password) {
      callback('确认两次输入的密码一致')
    }
    callback()
  }

  render() {
    const { handleCancel, roleList,storeList } = this.props;
    const { loading, dataSource } = this.state;
    return (
      <Form
        ref={(ref) => {
          this.formRef = ref;
        }}
        labelCol={{ span: 6 }}
        onFinish={this.onFinish}
        wrapperCol={{ span: 16 }}
        initialValues={{ status: 'Y' }}
      >
        <Item name="loginName"
          rules={[{ required: true, message: '请输入用户名' },
          { pattern: /^[0-9a-zA-Z]+$/, message: '只能输入数字与英文字母' }]}
          label={'用户名'}>
          <Input disabled={true} maxLength={16} placeholder={'请输入用户名'} />
        </Item>
        <Item name="passwdMd"
          rules={[{
            pattern: /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*()_.]+)$)^[\w~!@#$%^&*()_.]{8,16}$/,
            message: "密码应为字母，数字，特殊符号(~!@#$%^&*()_.)，两种及以上组合，8-16位字符串，如：abcd@1234"
          }]}
          label="密码">
          <React.FormPassword placeholder={'请输入8位以上密码，且含大小写字母、数字、特殊字符中的三种'} />
        </Item>
        <Item name="confirmPasswdMd"
          rules={[{ validator: this.validatePassword }]}
          label="确认密码">
          <React.FormPassword placeholder={'请确认密码'} />
        </Item>
        <Item name="userName" rules={[{ required: true, message: "请输入姓名" }, { max: 20 }]} label="姓名">
          <React.FormInput disabled={dataSource && dataSource.loginName === 'admin'} placeholder={'请输入姓名'} />
        </Item>
        <Item name="userMobile"
          rules={[{ required: true, message: "请输入手机号" }, { pattern: phoneReg, message: '请输入正确手机号' }]}
          label="手机号">
          <React.FormInput disabled={dataSource && dataSource.loginName === 'admin'} placeholder={'请输入手机号'} />
        </Item>

        <Item name="roleIds"
          rules={[{ required: true, message: "请选择角色" }]}
          label="角色">
          <React.FormSelect
            disabled={dataSource && dataSource.loginName === 'admin'}
            placeholder={'请选择角色'}
            options={roleList} />
        </Item>
        <Item name="storeId"
          // rules={[{ required: true, message: "请选择门店" }]}
          label="门店">
          <React.FormSelect
            allowClear={true}
            disabled={dataSource && dataSource.loginName === 'admin'}
            placeholder={'请选择门店'}
            options={storeList} />
        </Item>
        <div className="p-text-align">
          <Space size="large">
            <Button key="back" onClick={handleCancel}>
              取 消
            </Button>
            <Button loading={loading} type="primary" htmlType="primary">
              确 定
            </Button>
          </Space>
        </div>
      </Form>
    );
  }
}

UserUpdate.propTypes = {
  dialogType: PropTypes.string,
  handleCancel: PropTypes.func
};
UserUpdate.defaultProps = {};
const mapStateToProps = state => {
  return {
    user: state.user
  };
};
const mapDispatchToProps = dispatch => {
  return {};
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(UserUpdate));
